package cn.edu.ctbu.datajpa3.controller;

import cn.edu.ctbu.datajpa3.entity.Student;
import cn.edu.ctbu.datajpa3.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/students")
public class StudentController {

    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    // 显示所有学生信息（用于 Thymeleaf 页面）
    @GetMapping("/thymeleaf")
    public String showStudents(Model model) {
        model.addAttribute("students", studentService.findAll());
        return "student"; // 返回 Thymeleaf 模板名称
    }

    // 通过 AJAX 获取所有学生信息
    @GetMapping("/ajax")
    @ResponseBody
    public List<Student> getStudents() {
        return studentService.findAll();
    }

    // 按姓名查询学生信息
    @GetMapping("/search")
    @ResponseBody
    public List<Student> searchStudents(@RequestParam String name) {
        return studentService.findByName(name);
    }

    // 根据 ID 获取单个学生信息
    @GetMapping("/{id}")
    @ResponseBody
    public Student getStudentById(@PathVariable Integer id) {
        return studentService.findById(id);
    }

    // 添加学生信息（通过 AJAX 提交）
    @PostMapping
    @ResponseBody
    public void addStudent(@RequestBody Student student) {
        studentService.save(student);
    }

    // 更新学生信息
    @PutMapping("/{id}")
    @ResponseBody
    public void updateStudent(@PathVariable Integer id, @RequestBody Student student) {
        student.setId(id);
        studentService.save(student);
    }

    // 删除学生信息
    @DeleteMapping("/{id}")
    @ResponseBody
    public void deleteStudent(@PathVariable Integer id) {
        studentService.delete(id);
    }
}

